package com.qfedu.edu.orderservice.interceptor;

import com.qfedu.edu.exception.BusinessException;
import com.qfedu.edu.orderservice.slot.base.SlotChain;
import com.qfedu.edu.result.R;
import com.qfedu.edu.result.ResponseCode;
import com.qfedu.edu.utils.HttpResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xiaobobo
 * @title: GlobalInterceptor
 * @projectName seckill-fy-2401-parent
 * @description: 这个是订单服务全局的拦截器
 * 这个拦截器 会触发咋们的这个slot的执行
 * @date 2024/11/11  16:31
 */
@Component
public class GlobalInterceptor implements HandlerInterceptor {

    @Autowired
    private SlotChain slotChain;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //在这里来执行我们的代码
        try {
            slotChain.dealRequest(request,response);
            return true;
        }catch (Exception err){
            //还要去处理在这个消息是啥
            R error=null;
            if(err instanceof BusinessException){
                //说明抛出了业务异常
                BusinessException businessException= (BusinessException) err;
                error = R.error(businessException.getCode(), businessException.getMsg());
            }else{
                error = R.error(ResponseCode.SYSTEM_EXCEPTION);
            }
            //然后执行这个响应
            HttpResponseUtils.sendResponse(response,error);
            //肯定就不能放行
            return  false;
        }

    }
}
